import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { Link } from 'dva/router';
import { Button, Row, Col, Layout, Modal, Breadcrumb, Select, Icon, Form, Input, message, Card, Upload } from 'antd';
import reqwest from 'reqwest';
import inStyle from '../../styles/Info.less';
import style from '../../styles/Details.less';
import Reset from '../../styles/ResetInput.less';
// import createG2 from 'g2-react';
// import { Stat } from 'g2';
import enquire from 'enquire.js';
import { reqwest_post } from '../../utils/Reqwest.js';
const { Content, Footer } = Layout;
class Detail extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			list: window.sessionStorage['details'] == undefined || window.sessionStorage['details'] == "undefined" ? []: JSON.parse(window.sessionStorage['details']),
      width: 350,
      height: 350,
      plotCfg: {
        margin: 60,
      },
      rebate: false,
      _rabate: undefined,
      role: JSON.parse(window.localStorage['setting']).role,
      ydata: [
        { year:2017, area:'提成', profit: 10000 },
        { year:2017, area:'返利', profit: 6000 },
        { year:2017, area:'策略', profit: 30000 },
        { year:2017, area:'正常', profit: 7999 },
      ],
      previewVisible: false,
      previewImage: '',
      fileList: [],
      defaultFileList: [],
      updateUrl: null,
      deleteImageUrl: null,
      uploading: false,
		}
  }
	componentWillMount() {
    this.setState({ _rabate: this.state.list.rebate_1, updateUrl: window.host + '/api/orders/' + this.state.list.ID + '/upload_file', deleteImageUrl: '/api/orders/' + this.state.list.ID + '/delete_pictures', defaultFileList: this.state.list.pictures_info });
  }
  componentDidMount() {
    this.setState({ fileList: this.state.list.pictures_info });
  }
  deletePicture = (picture_id) => {
    const _this = this
    reqwest_post(_this.state.deleteImageUrl, {
      "picture_id": picture_id
    }, (data) => {
      console.log("datadatadata-deletePicture", data)
    })
  }
  handleSaveChange() {
    let _list = this.state.list;
    reqwest_post('/api/orders/update_rebate', {
      access_token: window.localStorage['token'],
      id: this.state.list.key,
      rebate: this.state._rabate,
    }, (data) => {
      if(data.status === 'success') {
        // this.state.list.rebate=this.state._rabate/100+'%';
        // this.state.list.rebate_1=this.state._rabate/100;
        // _list.strategy_result=this.state._rabate/100
        message.success('更新成功');
        this.setState({rebate:false});
      }
    })
  }
  handleCancel = () => this.setState({ previewVisible: false })
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  handleChange = ({ fileList }) => {
    if (fileList[0].response) {
      this.setState({ fileList: fileList[0].response.order.pictures_info });
    } else {
      this.setState({ fileList });
    }
  }
  payOrder() {
    const _this = this;
    reqwest_post('/api/orders/' + _this.state.list.ID + '/check_order', {}, (data) => {
      console.log('data', data)
      if (data.status === 'success') {
        message.success('付款成功！');
        window.history.go(-1);
      } else {
        message.error(data.msg);
      }
    })
  }
	render() {
    let _this = this;
    const { list, rebate, _rabate, previewVisible, previewImage, fileList, updateUrl, uploading } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const props = {
      action: updateUrl,
      listType: "picture-card",
      headers: {
        authorization: window.localStorage['token'],
      },
      fileList: fileList,
      name: 'image',
      onPreview: _this.handlePreview,
      onChange: _this.handleChange,
      onRemove: (file) => {
        _this.setState(({fileList}) => {
          _this.deletePicture(file.id);
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      // beforeUpload: (file) => {
      //   console.log('beforeUpload', file)
      //   _this.setState(({list}) => ({
      //     fileList: [...list, file],
      //   }));
      //   return false;
      // },
    };
    // let _money;
    let _role = this.state.role === 'admin' ? 'inline-block': 'none';
		// const _list = this.state.list.map(function(data){
		// 	return <Col  sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
		// 		<span>1</span>
		// 	</Col>
		// })
    const _money = list.strategy_result.map((data, index) => {
      if (data[0] !== '介绍人返利') {
        return (<Col key={index} className={`${inStyle.dea_list}`}>
          <span>{data[0]}：</span><span style={{color:'rgb(61, 189, 125)'}}>{data[1]}</span>
        </Col>)
      } else {
        return <Col key={index} className={`${inStyle.dea_list}  ${style.edit_input}`}>
          <span>{data[0]}：</span><span style={{color:'rgb(61, 189, 125)'}}>
            <label>
              {rebate==false?_rabate:<Input onChange={(e)=>{this.setState({_rabate:e.target.value});}}  addonAfter="%"  defaultValue={_rabate} />}
              {rebate==false?<strong onClick={()=>{this.setState({rebate:true})}} style={{marginLeft:'10px',color:'#108ee9',fontWeight:'normal',display:_role}}>编辑<Icon type='edit' /></strong>:<div><a onClick={()=>{this.handleSaveChange()}} >保存</a>
                  <span className="ant-divider" />
                <a onClick={()=>this.setState({rebate:false})}>返回</a>
              </div>}
            </label>
          </span>
        </Col>
      }
    })
    // for(let i in list.strategy_result){
    //   console.log(i)
    //   _money=(<Col className={`${inStyle.dea_list}`}>
    //     <span>{i}</span><span style={{color:'rgb(61, 189, 125)'}}>{list.strategy_result[i]}</span>
    //   </Col>)
    // }
		return (
			<Layout>
        <Layout.Content className={`${Reset.berad}`} >
          <Row>
            <Breadcrumb  className={`${Reset.blue_dia_none}`}>
              <Breadcrumb.Item ><span className={`${Reset.blue_dia}`}></span></Breadcrumb.Item>
              <Breadcrumb.Item className={`${Reset.bread_div} ${Reset.bread_div_first}`}>
                <Link to={{pathname:'/app/orders',query:{current:this.props.location.query.current}}}>订单</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item className={`${Reset.bread_div}`}>订单详情</Breadcrumb.Item>
            </Breadcrumb>
          </Row>
        </Layout.Content>
        <Content className={`${style.content}`}  style={{background:'#fff'}}>
          <Row>
            <Col className={`${inStyle.dea_list}`}>
              <span>订单号：</span>
              <span>{list.orders}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>品牌商：</span>
              <span>{list.company_name}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>渠道：</span>
              <span>{list.region}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>门店：</span>
              <span>{list.store}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>销售提成(%)：</span>
              <span>{list.store_rate}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <Row>
                <Col><span>买单凭证：</span></Col>
                <Col>
                  <Upload {...props}>
                    {fileList.length >= 8 ? null : uploadButton}
                  </Upload>
                  <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                  </Modal>
                </Col>
              </Row>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>姓名：</span>
              <span>{list.name}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>电话：</span><span>{list.tel==undefined?list.mobile:list.tel}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>面积：</span><span>{list.size}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>师傅：</span><span>{list.measure_master}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>预约测量时间：</span><span>{list.timer}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>地址：</span><span>{ list.province + list.city + list.area + list.street}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>订单状态：</span><span>{list.status}</span>
            </Col>
            <Col className={`${inStyle.dea_list}`}>
              <span>所属者：</span><span>{list.owner_name}</span>
            </Col>
          </Row>
          <Row>
            <Col style={{ padding: '3vh 25px', borderBottom: '1px dashed #d9d9d9' }}>
              <Breadcrumb style={{ fontSize: 16 }}>
                <Breadcrumb.Item>收支款明细</Breadcrumb.Item>
              </Breadcrumb>
            </Col>
          </Row>
          <Row>
            {_money}
          </Row>
          <Row>
            <Col className={`${inStyle.dea_list}`} style={{ display: list.status === '预约安装' ? 'block' : 'none' }}>
              <Button type="primary" onClick={this.payOrder.bind(this)}>付款</Button>
            </Col>
          </Row>
        </Content>

      </Layout>
		)
	}
}
        // <Footer className={`${style.page}`} >
        //   <span>
        //     <Link to={{pathname:this.props.location.query.ma,query:{wudi:this.props.location.query.wudi,name:list.name,mobile:list.tel==undefined?list.mobile:null}}}>编辑</Link>
        //   </span>
        // </Footer>
export default connect()(Detail);
